<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <div class="m-4 mr-0 overflow-hidden bg-white">
      <BasicTree title="部门列表" toolbar checkable search treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
        :clickRowToExpand="false" :treeData="treeData" :fieldNames="{ key: 'deptId', title: 'name' }"
        v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys" @select="handleSelect" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, onMounted } from 'vue';

import { getAllDeptListApi, getAllDeptApi } from '@/api/sys/sysData';
import { formSchema } from './role.data';
// @select="handleSelect"

import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicTree, TreeItem } from '@/components/Tree';
import { setDeptsApi, getDeptIdsApi } from '@/api/sys/chatGroup';
import { Form, FormItem } from 'ant-design-vue';
import { useMessage } from "@/hooks/web/useMessage";

import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);

const deptList = ref([]);

const { createMessage } = useMessage();

const openConversationId = ref("");

const formData = ref({})
const selectedKeys = ref([]);
const checkedKeys = ref([]);

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  setModalProps({ confirmLoading: false });
  selectedKeys.value = [];
  checkedKeys.value = [];
  getDeptIdsApi(data.record).then((res) => {
    if (res.code == 200) {
      let arr = [];
      for (let a = 0; a < res.data.length; a++) {
        let element = res.data[a];
        arr.push(element);
      }
      selectedKeys.value = arr;
      checkedKeys.value = arr;
      console.log("---arr:", arr);

      formData.value.openConversationId = data.record.openConversationId
      formData.value.deptNames = data.record.deptNames;
    } else {
      createMessage.error(res.message);
    }
  })

});

const getTitle = "设置部门(后续有新员工入职可自动加入群)";

async function handleSubmit() {
  try {
    // console.log("--selectedKeys::", selectedKeys.value);
    // console.log("--checkedKeys::", checkedKeys.value);
    if (checkedKeys.value.length == 0) {
      createMessage.error("请选择部门!");
      return;
    }
    let arr = [];
    for (let a = 0; a < checkedKeys.value.length; a++) {
      let key = checkedKeys.value[a];
      let result = getDeptNameByDeptId(key);
      if (result) {
        arr.push(result.name)
      }
    }
    formData.value.deptIds = checkedKeys.value.join(",");
    formData.value.deptNames = arr.join(",");
    const values = formData.value;
    // console.log("--values:", values);

    setModalProps({ confirmLoading: true });
    setDeptsFn(values);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}


async function fetch() {
  await getAllDeptListApi().then(res => {
    if (res.code == 200) {
      treeData.value = res.data;
    } else {
      createMessage.error(res.message);
    }
  })

}

async function getAll() {
  await getAllDeptApi().then(res => {
    if (res.code == 200) {
      deptList.value = res.data;


    } else {
      createMessage.error(res.message);
    }
  })

}

function getDeptNameByDeptId(id) {
  let result = null;
  for (let a = 0; a < deptList.value.length; a++) {
    let element = deptList.value[a];
    if (id == element.deptId) {
      result = element;
      break;
    }
  }
  return result;
}


function setDeptsFn(values) {
  setDeptsApi(values).then((res) => {
    // console.log("---res::",res)
    if (res.code == 200) {
      createMessage.success(res.message);
    } else {
      createMessage.error(res.message);
    }
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      closeModal();
      emit('success');
    });
}


function userSelectSuccessFn(e) {

  formData.value.deptIds = e.ids;
  formData.value.userName = e.names;

}
function handleSelect(keys, obs) {

}

onMounted(() => {
  fetch();
  getAll()
});

</script>
